package cn.cmdr.controller;

import cn.cmdr.pojo.Journal;
import cn.cmdr.pojo.Staff;
import cn.cmdr.pojo.User;
import cn.cmdr.service.JournalService;
import cn.cmdr.service.UserService;
import cn.cmdr.vo.ResultVo;
import cn.cmdr.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/jur/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private JournalService journalService;
    @PostMapping("/userList")
    public ResultVo getUserList(){
        List<User> list = userService.getUserList();
        return ResultVo.sucess(list);
    }
    //    @GetMapping("/userlist")
//    public Object getList(){
//        return userService.getUserList();
//    }
    //添加
    @PostMapping("/add")
    @RequiresPermissions("user:add")
    public ResultVo add(@RequestBody User user){
        try{
            if(user.getUserCode()==null){
                return ResultVo.fail("账号不能为空!");
            }
            if(user.getUserName()==null){
                return ResultVo.fail("姓名不能为空!");
            }
            if(user.getPassword()==null){
                return ResultVo.fail("密码不能为空!");
            }
            String pass = new Md5Hash(user.getPassword(),"qwer").toString();
            System.out.println(pass);
            user.setPassword(pass);
            user.setSalt("qwer");
            user.setCreatedDate(new Date());
            userService.add(user);
            return ResultVo.sucess("角色添加成功!");
        }catch(Exception e){
            return ResultVo.fail("角色添加失败了",e);//包含了打印错误日志
        }
    }
    //修改
    @PostMapping("/update")
    @RequiresPermissions("user:update")
    public ResultVo update(@RequestBody User user){
        try{
            user.setModifyDate(new Date());
            userService.update(user);
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("修改订单:"+user.getUserName());
            journal.setMenuId(9);
            journalService.add(journal);
            return ResultVo.sucess("角色修改成功！");
        }catch(Exception e){
            return ResultVo.fail("角色添加失败了",e);//包含了打印错误日志
        }
    }
    //分页
    @PostMapping("/list/{pageSize}/{pageNo}")
    public ResultVo getUserList(@PathVariable Integer pageSize,@PathVariable Integer pageNo,@RequestBody UserVo userVo){
        return ResultVo.sucess(userService.getPageUserList(pageNo,pageSize,userVo));
    }

}
